#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.common.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Description: 流式响应工具类
 *
 * @author wenxiaopeng
 * @date 2021/06/16 18:51
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
public class ResponseUtil {

	@SneakyThrows
	public static void setFileHeader(HttpServletResponse response, String fileName) {
		response.setContentType("application/x-download;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
		response.addHeader("Pargam", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
	}

	/**
	 * Description:
	 * <>
	 * @param response 1
	 * @param inputStream 2
	 * @param fileName 3
	 * @author wenxiaopeng
	 * @date 18:17 2021/06/16
	 **/
	public static void response(HttpServletResponse response, InputStream inputStream, String fileName) {
		setFileHeader(response, fileName);
		try(OutputStream out = response.getOutputStream()) {
			byte[] buff = new byte[1024];
			int length;
			while ((length = inputStream.read(buff)) > 0) {
				out.write(buff, 0, length);
			}
			IOUtils.closeQuietly(inputStream);
			out.flush();
		} catch (IOException e) {
			log.error("error info ",e);
		}
	}

	/**
	 * 以ResponseEntity形式返回字节流
	 * @param inputStream       InputStream Of File
	 * @param fileName          File Name
	 * @author wenxiaopeng
	 * @date 2021/07/19 09:00
	 * @return org.springframework.http.ResponseEntity<byte[]>
	 **/
	public static ResponseEntity<byte[]> response(InputStream inputStream, String fileName) throws IOException {
		if(null != inputStream) {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			IOUtils.copy(inputStream, output);
			// 文件名转码
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Disposition", "attachment;filename="
					+ new String(fileName.getBytes(UTF_8), ISO_8859_1));
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return new ResponseEntity<>(output.toByteArray(), headers, HttpStatus.OK);
		}
		return null;
	}
}
